
import 'package:date_format/date_format.dart';
import 'package:elevator/dio/api.dart';
import 'package:elevator/get/intl_keys.dart';
import 'package:elevator/pages/testing/testing_view.dart';
import 'package:elevator/pages/testing/webviewtest.dart';
import 'package:elevator/utils/utils_dialog.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mysql1/mysql1.dart';

import '../../model/user.dart';
import '../main/home/home_view.dart';
import 'login_state.dart';

import 'package:mysql1/mysql1.dart' as mysql;


class LoginLogic extends GetxController {
  final LoginState state = LoginState();


  ///登陆按钮点击事件
  login(BuildContext context,TextEditingController userNameController, TextEditingController passWordController) {
    var userName = userNameController.text;
    var passWord = passWordController.text;

    FocusScope.of(context).requestFocus(FocusNode());
    ///2-用户名判断
    if(userName.isEmpty){
      Get.snackbar(IntlKeys.wrongName.tr, IntlKeys.nameNotEmpty.tr,snackPosition: SnackPosition.TOP);
      return;
    }
    ///3-密码判断
    if(passWord.isEmpty){
      Get.snackbar(IntlKeys.pwdWrong.tr, IntlKeys.pwdNotEmpty.tr,snackPosition: SnackPosition.TOP);
      return;
    }
    print("用户名:$userName,密码：$passWord");
    doLogin(context,userName, passWord);
   // Get.off(HomePage());
  }

  void changeChecked(bool value) {
    state.showPassword.value = value;
    update();
  }

  void doLogin(BuildContext context,String psName,String psWord) {
    /*if (!kReleaseMode) {
      Get.off(() => HomePage());
      return;
    }*/
    final List<User> userList = [];
    UtilsDialog.showLoadingDialog(context, content: IntlKeys.loginig.tr);
    queryUserInfo(psName, psWord).then(
        (value) => {
              Navigator.pop(context),
              print("then:" + value!.toString()),
              if (value == null)
                {
                  Get.snackbar(IntlKeys.loginFailure.tr, IntlKeys.wrongNameOrPwd.tr,
                      snackPosition: SnackPosition.TOP),
                }
              else
                {
                  for (var row in value)
                    {
                      print('id: ${row[0]}, psWord: ${row[1]}, psName: ${row[2]}, psAuth: ${row[3]}, psBuilds: ${row[4]}'),
                      userList.add(User(id:row[0],
                          psWord:row[1].toString(),
                          psName:row[2].toString(),
                          psAuth:row[3],
                          psBuilds:row[4].toString(),
                          psStartDate:formatDate(row[5], [yyyy, '-', mm, '-', dd]),
                          psExDate:formatDate(row[6], [yyyy, '-', mm, '-', dd]),
                          psStatus:row[7],
                          psErrCnt:row[8],
                          psFirstName:row[9].toString(),
                          psLastName:row[10].toString(),
                          psPhoneNum:row[11].toString(),
                          tokenID:row[12].toString(),
                          sysType:row[13]) ),
              },
              if(userList.length==1){
                state.user = userList[0],
                print(state.user),
                Get.off(() => HomePage(),arguments: userList[0])
                // Get.off(() => TestingPage(),arguments: userList[0])
                // Get.off(() => MyWebView())
              }else {
                Get.snackbar(IntlKeys.loginFailure.tr, IntlKeys.wrongNameOrPwd.tr,snackPosition: SnackPosition.TOP)
              }
            }
        },
        onError: (e){
          Navigator.pop(context);
      print("onError:" + e.toString());
      Get.snackbar(IntlKeys.loginFailure.tr, IntlKeys.serverError.tr, snackPosition: SnackPosition.TOP);
    }
    ).whenComplete(() => {
      print('Complete'),
    });
  }

  Future queryUserInfo(String psName,String psWord) async {
    print("start queryUserInfo");
    var settings = mysql.ConnectionSettings(
        host: '36.141.45.30',
        port: 43306,
        user: 'root',
        password: 'adminemqx123',
        db: 'RegInfo',
        useCompression: false,
        timeout:const Duration(seconds: 60),
        maxPacketSize:16 * 1024 * 1024 *1024,
        characterSet: CharacterSet.UTF8MB4);
    var conn = await mysql.MySqlConnection.connect(settings);

    var result = await conn
        .query('select * from tbPassWord where psName=? and psWord=? limit 2',[psName,psWord]);
    debugPrint(result!.toString());
    await conn.close();
    // var result = await httpManager.netFetch('http://www.baidu.com');
    return result;
  }
}

